﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;

namespace QAToolsAddin.Components {
    public partial class ExcelListNames : UserControl {
        List<Excel.Name> _thisNames;

        public event EventHandler SelectedIndexChanged;

        public ExcelListNames() {
            InitializeComponent();
        }

        private void ExcelListNames_Load(object sender, EventArgs e) {
            if (ParentForm is ExcelForm == false)
                throw new ArgumentException("An ExcelForm parent type is required.");
        }

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Excel.Names Names {
            set {
                SuspendLayout();
                listView1.Items.Clear();
                if (value != null) {
                    _thisNames = new List<Excel.Name>();
                    foreach (Excel.Name name in value)
                        if (name.Visible) {
                            _thisNames.Add(name);
                            listView1.Items.Add(name.Name.PadRight(Math.Max(20 - name.Name.Length, 0), ' '));
                        }
                }
                ResumeLayout();
            }
        }

        public void CheckAll() {
            foreach (ListViewItem item in listView1.Items)
                item.Checked = true;
        }

        public void UncheckAll() {
            foreach (ListViewItem item in listView1.Items)
                item.Checked = false;
        }

        public void Clear() {
            listView1.Items.Clear();
        }

        [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Excel.Name SelectedName {
            get {
                return _thisNames[listView1.SelectedIndices[0]];
            }
        }

        [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Excel.Name[] CheckedNames {
            get {
                var names = new Excel.Name[listView1.CheckedIndices.Count];
                int pos = -1;
                foreach (int index in listView1.CheckedIndices)
                    names[++pos] = _thisNames[index];
                return names;
            }
        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e) {
            SelectedIndexChanged(sender, e);
        }

    }
}
